package com.tianheng.wanzhou.datacollecting.netty.xishaji;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tianheng.wanzhou.datacollecting.db.entity.MachineList;
import com.tianheng.wanzhou.datacollecting.db.entity.Xishaji;
import com.tianheng.wanzhou.datacollecting.db.service.IMachineListService;
import com.tianheng.wanzhou.datacollecting.db.service.IXishajiService;
import com.tianheng.wanzhou.datacollecting.util.SerializeUtil;
import com.tianheng.wanzhou.datacollecting.util.StrUtil;
import com.tianheng.wanzhou.datacollecting.util.TqlHexchange;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;


@Slf4j
@Component(value = "xishajiHandler")
@Scope("prototype")
public class ClientHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    IXishajiService xishajiService;
    @Autowired
    IMachineListService machineListService;
    private List<MachineList> machineList = new ArrayList<>();

//    @Resource
//    Jedis jedis;

    private static ClientHandler clientHandler;

    @PostConstruct
    public void init() {
        clientHandler = this;
        xishajiService = this.xishajiService;
//        jedis = this.jedis;
        QueryWrapper<MachineList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mac_type", 7).eq("status", 1);
        machineList = machineListService.list(queryWrapper);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = insocket.getAddress().getHostAddress();
        log.info("连接服务端" + clientIP + "成功!");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = insocket.getAddress().getHostAddress();
        // redis 线程锁 超时3秒清楚Lock
//        while(jedis.setnx("lock",String.valueOf(System.currentTimeMillis() + 3000))==0){
//            if (System.currentTimeMillis()>Long.valueOf(jedis.get("lock")) && System.currentTimeMillis()>Long.valueOf(jedis.getSet("lock",String.valueOf(System.currentTimeMillis() + 3000))) ){
//                break;
//            }else {
//                Thread.sleep(300);
//            }
//        }
//        MachineList machine = (MachineList) SerializeUtil.deserialize(jedis.get(clientIP.getBytes()));
//        jedis.del("lock");
        try {
            MachineList machine = new MachineList();
            for (MachineList machine1 : this.machineList) {
                if(clientIP.equals(machine1.getMacIp())){
                    machine =machine1;
                    break;
                }
            }
            ByteBuf buf = (ByteBuf)msg;
            byte[] bytes = new byte[buf.readableBytes()];
            buf.readBytes(bytes);
            String str = StrUtil.bytesToHexString(bytes);
            log.info("收到数据:" + str);
            Xishaji xishaji = new Xishaji();
//            xishaji.setMachineIp(clientIP);
            xishaji.setMachineIp(machine.getMacIp());
            xishaji.setMacId(machine.getMacId());
            String data = str.substring(18);
            xishaji.setCurrentNumberTube(TqlHexchange.zcString(data.substring(0,4)));
            xishaji.setCopLength(TqlHexchange.zcString(data.substring(68,72)));
            xishaji.setClassAShiftProduction(TqlHexchange.zcString(data.substring(72,80)));
            xishaji.setClassACumulativeProduction(TqlHexchange.zcString(data.substring(80,88)));
            xishaji.setTotalLengthCumulative(TqlHexchange.zcString(data.substring(88,96)));
            xishaji.setClassBShiftProduction(TqlHexchange.zcString(data.substring(96,104)));
            xishaji.setClassBCumulativeProduction(TqlHexchange.zcString(data.substring(104,112)));
            xishaji.setClassCShiftProduction(TqlHexchange.zcString(data.substring(112,120)));
            xishaji.setClassCCumulativeProduction(TqlHexchange.zcString(data.substring(120,128)));
            //xishaji.setClassDShiftProduction(TqlHexchange.zcString(data.substring(128,136)));
            xishaji.setClassDCumulativeProduction(TqlHexchange.zcString(data.substring(136,144)));
            xishaji.setRolledPlateDiameter(TqlHexchange.zcString(data.substring(144,148)));
            xishaji.setWharveDiameter(TqlHexchange.zcString(data.substring(148,152)));
            xishaji.setRolledSpeed(TqlHexchange.zcString(data.substring(160,164)));
            xishaji.setSpindleSpeed(TqlHexchange.zcString(data.substring(164,168)));
            xishaji.setYarnNumber(TqlHexchange.zcString(data.substring(176,180)));
            xishajiService.saveOrUpdate(xishaji);

        }finally {
            ReferenceCountUtil.release(msg);
        }
        ctx.channel().close();
        ctx.close();

    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        log.info("数据读取完毕");
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = insocket.getAddress().getHostAddress();
        log.info("连接"+ clientIP +"移除");

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("发生错误:" + cause.toString());
        ctx.close();
    }

}
